package com.yxy.service;

import com.github.pagehelper.PageHelper;
import com.yxy.base.BusinessException;
import com.yxy.dao.SysLogsMapper;
import com.yxy.feign.VO.AdminUserInToken;
import com.yxy.model.SysLogs;
import com.yxy.utils.TokenCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class SysLogsService {

  @Autowired
  private TokenCheckUtil tokenCheckUtil;
  @Resource
  private SysLogsMapper SysLogsMapper;

  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public SysLogs save(SysLogs pojo) throws BusinessException {
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    SysLogs entity = new SysLogs();
    BeanUtils.copyProperties(pojo, entity);
    entity.setCreateDate(new Date());
    entity.setCreateUserId(adminUser.getAdminUser().getId());
    entity.setCreateUserName(adminUser.getAdminUser().getUsername());
    entity.setUserName(adminUser.getAdminUser().getUsername());
    SysLogsMapper.insertSelective(entity);
    return entity;
  }

  public List<SysLogs> getlist(SysLogs query) throws BusinessException {
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    // 处理tenant id list
    Set<Long> tenantIdList = new HashSet<>();
    Long tenantId = query.getTenantId();
    if (tenantId == null) {// 取出用户所属租户下所有的数据
      tenantIdList = adminUser.getTenantIdList();
    } else {
      if (!adminUser.getTenantIdList().contains(tenantId)) { // 判断前端传递的tenantId是否属于该用户
        throw new BusinessException(510, "前端传递的tenantId不属于该用户");
      }
      tenantIdList.add(tenantId);
    }
    query.setTenantIdList(tenantIdList);
    PageHelper.startPage(query.getPageNumber(), query.getPageSize());
    PageHelper.orderBy("t1.create_date desc");//排序
    List<SysLogs> dbResult = SysLogsMapper.selectList(query);
    return dbResult;
  }

}
